//
//  MCWithdrawRecDeltailViewController.m
//  TLYL
//
//  Created by miaocai on 2017/7/10.
//  Copyright © 2017年 TLYL01. All rights reserved.
//

#import "MCWithdrawRecDeltailViewController.h"
#import "MCBankTableViewController.h"
#import "MCSelectedBottomView.h"
#import "NSString+Helper.h"
#import "MCUserMoneyModel.h"
#import "MCWithdrawAPIModel.h"
#import "MCMineInfoModel.h"
#import "MCDataTool.h"

@interface MCWithdrawRecDeltailViewController ()
<
MCSelectedBottomDelegate
>



@property (weak, nonatomic)  UILabel *moneyLabel;
@property (weak, nonatomic)  UIButton *allBtn;
@property (weak, nonatomic)  UITextField *moneyTextField;
@property (weak, nonatomic)  UITextField *passwordTextField;

@property (weak, nonatomic)  UIButton *withdrawBtn;
@property (weak, nonatomic)  UIButton *bankBtn;

@property (nonatomic,strong)MCBankModel *selectModel;
@property (nonatomic,strong)MCUserMoneyModel * money_model;
@property (nonatomic,strong)MCWithdrawAPIModel * apiModel;
@property (nonatomic,strong)UIImageView * bankImgV;

//提现最小值
@property (nonatomic,assign)int DrawMinMoney;
//提现最大值
@property (nonatomic,assign)int DrawMaxMoney;

@end

@implementation MCWithdrawRecDeltailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setUpUI];
    self.navigationItem.title = @"提款";
    self.view.backgroundColor = [UIColor whiteColor];
    [self loadData];
 
}


-(void)viewWillAppear:(BOOL)animated{
    self.navigationController.navigationBarHidden=NO;
    self.navigationController.navigationBar.translucent = NO;
    [self reloadUserMoney];
}



- (void)setUpUI{
    
    _selectModel=[[MCBankModel alloc]init];

    
/********************1*********************/
    UIView * view1=[[UIView alloc]init];
    [self.view addSubview:view1];
    view1.backgroundColor=[UIColor whiteColor];
    view1.frame=CGRectMake(0, 0, G_SCREENWIDTH, 41);
    
    UILabel *jinELabel = [[UILabel alloc] init];
    jinELabel.textColor = RGB(54, 128, 221);
    [view1 addSubview:jinELabel];
    jinELabel.textAlignment = NSTextAlignmentCenter;
    jinELabel.text = @"加载中...";
    jinELabel.font = [UIFont boldSystemFontOfSize:MC_REALVALUE(20)];
    _moneyLabel=jinELabel;
    
    
    
    UILabel *jinEDetailLabel = [[UILabel alloc] init];
    jinEDetailLabel.textColor = RGB(119, 119, 119);
    [view1 addSubview:jinEDetailLabel];
    jinEDetailLabel.text = @" 账户余额(元)";
    jinEDetailLabel.font = [UIFont systemFontOfSize:MC_REALVALUE(12.0f)];
    
    [jinELabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(view1).offset(MC_REALVALUE(10));
        make.top.bottom.equalTo(view1);
    }];
    
    [jinEDetailLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(jinELabel.mas_right);
        make.top.bottom.equalTo(jinELabel);
    }];
    
/********************2*********************/    
    UIView * view2=[[UIView alloc]init];
    [self.view addSubview:view2];
    view2.backgroundColor=RGB(242, 242, 242);
    view2.frame=CGRectMake(0, 41, G_SCREENWIDTH, 110);
    
    UIImageView * imgV=[[UIImageView alloc]init];
    [view2 addSubview:imgV];
    imgV.backgroundColor=[UIColor clearColor];
    imgV.frame=CGRectMake(10, 10, 25, 25);
    _bankImgV=imgV;
    
    UIButton *bankBtn = [[UIButton alloc] init];
    [view2 addSubview:bankBtn];
    
    [bankBtn setTitle:@"加载中..." forState:UIControlStateNormal];
    [bankBtn setTitleColor:RGB(68, 68, 68) forState:UIControlStateNormal];
    bankBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    bankBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    bankBtn.backgroundColor = [UIColor clearColor];
    bankBtn.frame=CGRectMake(50, 0, G_SCREENWIDTH-50, 45);
    _bankBtn=bankBtn;
    

    
    
    UIView *lineView1 = [[UIView alloc] init];
    [view2 addSubview:lineView1];
    lineView1.backgroundColor = RGB(214, 221, 228);
    lineView1.frame=CGRectMake(0, 45, G_SCREENWIDTH, 0.5);
    
    UIImageView * imgV_RMB=[[UIImageView alloc]init];
    [view2 addSubview:imgV_RMB];
    imgV_RMB.image=[UIImage imageNamed:@"WithdrawMoney"];
    imgV_RMB.frame=CGRectMake(10+3, 45+20, 18.5, 25);
    
    /*
     *  金额
     */
    UITextField *rmbTextFiled = [[UITextField alloc] init];
    [view2 addSubview:rmbTextFiled];
    [self setTextField:rmbTextFiled WithPlaceholder:@"单笔提款金额范围为：加载中..." and:UIKeyboardTypeDecimalPad andIndex:0];
    rmbTextFiled.frame=CGRectMake(50, 45, G_SCREENWIDTH-120, 65);
    self.moneyTextField=rmbTextFiled;
    rmbTextFiled.tag=1001;
    _moneyTextField=rmbTextFiled;

    UIButton *allBtn = [[UIButton alloc] init];
    [view2 addSubview:allBtn];
    [allBtn setTitle:@"全部转出" forState:UIControlStateNormal];
    allBtn.titleLabel.font = [UIFont systemFontOfSize:MC_REALVALUE(14)];
    [allBtn setTitleColor:RGB(54, 128, 221) forState:UIControlStateNormal];
    [allBtn addTarget:self action:@selector(allBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    allBtn.frame=CGRectMake(G_SCREENWIDTH-70, 45, 60, 65);

/********************3*********************/
    UIView *view3=[[UIView alloc]init];
    [self.view addSubview:view3];
    view3.backgroundColor=RGB(242, 242, 242);
    view3.frame=CGRectMake(0, 41+110+5, G_SCREENWIDTH, 45);
    
    
    /*
     * 密码
     */
    UITextField *pwdTf = [[UITextField alloc] init];
    [view3 addSubview:pwdTf];
    pwdTf.frame=CGRectMake(10, 0, G_SCREENWIDTH-20, 45);
    [self setTextField:pwdTf WithPlaceholder:@"请输入资金密码" and:UIKeyboardTypeDefault andIndex:0];
    pwdTf.tag=1003;
    _passwordTextField=pwdTf;
    [pwdTf setAutocorrectionType:UITextAutocorrectionTypeNo];
    [pwdTf setAutocapitalizationType:UITextAutocapitalizationTypeNone];
    pwdTf.secureTextEntry = YES;
    
    UIButton *tikuanBtn = [[UIButton alloc] init];
    [self.view addSubview:tikuanBtn];
    [self setFooter:tikuanBtn];
    tikuanBtn.frame=CGRectMake(10, 295, G_SCREENWIDTH-20, 50);
    
    

    tikuanBtn.backgroundColor = [UIColor blueColor];
    
    UILabel *infoLabel = [[UILabel alloc] init];
   NSString *DrawBeginTime = [[NSUserDefaults standardUserDefaults] objectForKey:@"DrawBeginTime"];
    NSString *DrawEndTime = [[NSUserDefaults standardUserDefaults] objectForKey:@"DrawEndTime"];
    if ([DrawBeginTime isEqualToString:DrawEndTime]) {
        infoLabel.text = @"取款到账时间为1-5分钟，取款时间为:全天24小时";
    } else {
        infoLabel.text = [NSString stringWithFormat:@"取款到账时间为1-5分钟，取款时间为:%@~%@", [self timeStr:[DrawEndTime intValue]],[self timeStr:[DrawBeginTime intValue]]];
    }
    
    infoLabel.textAlignment = NSTextAlignmentCenter;
    infoLabel.textColor = RGB(68, 68, 68);
    infoLabel.font = [UIFont systemFontOfSize:MC_REALVALUE(12)];
    [self.view addSubview:infoLabel];
    infoLabel.frame = CGRectMake(0, G_SCREENHEIGHT - 40 - 64, G_SCREENWIDTH, 20);
    

    UITapGestureRecognizer *singleTapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(closeKeyboard:)];
    singleTapGesture.numberOfTapsRequired = 1;
    singleTapGesture.cancelsTouchesInView = NO;
    [self.view  addGestureRecognizer:singleTapGesture];
    
    
    
}
- (NSString *)timeStr:(int)drawTime{
    
        if(drawTime>=0 && drawTime < 6){
            return [NSString stringWithFormat:@"凌晨%d:00",drawTime];
        }else if (drawTime>=6 && drawTime < 12){
            return [NSString stringWithFormat:@"上午%d:00",drawTime];

        }else if (drawTime>=12 && drawTime < 18){
            return [NSString stringWithFormat:@"下午%d:00",drawTime];
   
        }else{
            return [NSString stringWithFormat:@"晚上%d:00",drawTime];
        }
}

#pragma mark - gesture actions
- (void)closeKeyboard:(UITapGestureRecognizer *)recognizer {
    [self.view endEditing:YES];
}

-(void)setFooter:(UIButton *)btn{
    
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [btn setTitle:@"提款" forState:UIControlStateNormal];
    btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    btn.contentEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
    [btn setBackgroundImage:[UIImage imageNamed:@"Button_Determine"] forState:UIControlStateNormal];

    [self.view addSubview:btn];
    [btn addTarget:self action:@selector(withdrawBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    btn.layer.cornerRadius=10.0;
    btn.clipsToBounds=YES;

}

/*
 * 输入框设置
 */
-(void)setTextField:(UITextField*)textField WithPlaceholder:(NSString *)placeholder and:(UIKeyboardType)type andIndex:(int)index {
    textField.placeholder=placeholder;
    textField.borderStyle = UITextBorderStyleNone;
    textField.backgroundColor=[UIColor clearColor];
    textField.font = [UIFont systemFontOfSize:14];
    textField.textColor = RGB(40, 40, 40);
    textField.textAlignment = NSTextAlignmentLeft;
    textField.returnKeyType = UIReturnKeyDone;
    textField.keyboardType = type;
    [textField setValue:RGB(190, 190, 190) forKeyPath:@"_placeholderLabel.textColor"];
    [textField setValue:[UIFont systemFontOfSize:14] forKeyPath:@"_placeholderLabel.font"];
    
    [textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:(UIControlEventEditingChanged)];
    
    
}

#pragma mark-loadData
-(void)loadData{

    MCMineInfoModel *mineInfo_model = [MCMineInfoModel sharedMCMineInfoModel];

    _bankImgV.image=[UIImage imageNamed:mineInfo_model.BankCode];
    NSString * bank;
    if (mineInfo_model.BankCardNumber.length>4) {
        NSString * bankNumber=[mineInfo_model.BankCardNumber substringFromIndex:mineInfo_model.BankCardNumber.length-4];
        bank=[NSString stringWithFormat:@"%@(%@)",[MCDataTool MC_GetDic_Bank][mineInfo_model.BankCode][@"name"],bankNumber];
    }else{
        bank=[NSString stringWithFormat:@"%@",[MCDataTool MC_GetDic_Bank][mineInfo_model.BankCode][@"name"]];
    }
    
    
    [_bankBtn setTitle:bank forState:UIControlStateNormal];
    
    _moneyTextField.placeholder=[NSString stringWithFormat:@"单笔提款金额范围为：%@-%@元",mineInfo_model.DrawMinMoney,mineInfo_model.DrawMaxMoney];
    
    _DrawMinMoney=[mineInfo_model.DrawMinMoney intValue];
    _DrawMaxMoney=[mineInfo_model.DrawMaxMoney intValue];
    
//    function time2Str(drawTime){
//        if(parseInt(drawTime)>=0 && parseInt(drawTime) < 6){
//            return "凌晨"+drawTime+":00";
//        }else if(parseInt(drawTime)>=6 && parseInt(drawTime) < 12){
//            return "上午"+drawTime+":00";
//        }else if(parseInt(drawTime)>=12 && parseInt(drawTime) < 18){
//            return "下午"+drawTime+":00";
//        }else if(parseInt(drawTime)>=18 && parseInt(drawTime) <= 24){
//            return
//            刘毅  14:30
//            "晚上"+drawTime+":00";
//        }
//    }
//
//    if(drawEndTime==drawBeginTime) 显示为 "全天24小时"
}

-(void)textFieldDidChange:(UITextField *)textField{
    
    if (textField.tag==1001) {
        if (textField.text.length == 1 && [textField.text isEqualToString:@"."]) {
            textField.text = @"0.";
        }
       NSArray *arr = [textField.text componentsSeparatedByString:@"."];
        
        float max = [textField.text floatValue];
        if (max>= _DrawMaxMoney) {
            max = _DrawMaxMoney;
            textField.text =[NSString stringWithFormat:@"%d",_DrawMaxMoney];
        }
        if (arr.count >1) {
            
            NSString *str = arr[1];
            if (str.length > 2) {
               str = [str substringWithRange:NSMakeRange(0, 2)];
            }
            textField.text = [NSString stringWithFormat:@"%@.%@",arr[0],str];
            
            NSString * str1=arr[0];
            if ([str1 isEqualToString:[NSString stringWithFormat:@"%d",_DrawMaxMoney]]) {
                textField.text = [NSString stringWithFormat:@"%d",_DrawMaxMoney];
            }
        }

        
    }else if(textField.tag==1002){
        
    }else if(textField.tag==1003){
        
    }
    
}



#pragma  mark-提款
- (void)withdrawBtnClick:(UIButton *)sender {

    if (!self.moneyTextField.text||[self.moneyTextField.text isEqualToString:@""]) {
        [SVProgressHUD showErrorWithStatus:@"请输入提款金额！"];
        return;
    }

    if (!self.passwordTextField.text||[self.passwordTextField.text isEqualToString:@""]) {
        [SVProgressHUD showErrorWithStatus:@"请输入资金密码！"];
        return;
    }
    
    NSString * jinE=_moneyTextField.text;
    NSString * password=_passwordTextField.text;
    
    NSLog(@"金额：%@-密码：%@",jinE,password);
    //UserRealName	是	String	用户真实姓名
    //DrawingsMoney	是	String	提款金额
    //PayPassWord	是	String	提款密码（资金密码）
    
    if ([jinE floatValue]>_DrawMaxMoney||[jinE floatValue]<_DrawMinMoney) {
        [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"提现范围%d-%d元",_DrawMinMoney,_DrawMaxMoney]];
        return;
    }
    MCMineInfoModel *mineInfoModel =[MCMineInfoModel sharedMCMineInfoModel];
    NSDictionary * dic=@{
                         @"UserRealName":mineInfoModel.UserRealName,
                         
//                          @"UserRealName":@"Xiamo",
                         @"DrawingsMoney":jinE,
                         @"PayPassWord":password
                         };
  
    MCWithdrawAPIModel  * apiModel = [[MCWithdrawAPIModel alloc]initWithDic:dic];
    self.apiModel = apiModel;
    [apiModel refreashDataAndShow];
    
    apiModel.callBackFailedBlock = ^(ApiBaseManager *manager, NSString *errorCode) {
      
    };
    
//    __weak __typeof__ (self) wself = self;
    apiModel.callBackSuccessBlock = ^(id manager) {
        
        //提现成功   清空输入框
        _moneyTextField.text=@"";
        _passwordTextField.text=@"";
        
        // 刷新用户金额
        [self reloadUserMoney];
        
        ApiBaseManager *manage=manager;
        if (manager) {
            if (manage.responseMessage) {
                NSLog(@"%@",manage.responseMessage);
                
 
                [self performSelector:@selector(delayMethod:) withObject:manage.responseMessage afterDelay:0.05];
            }
        }
    };
    
}
-(void)delayMethod:(NSString * )noti{
    [SVProgressHUD showSuccessWithStatus:noti];
}
#pragma mark-全部提出
- (void)allBtnClick:(UIButton *)sender {

    NSString * allMoney=[_moneyLabel.text stringByReplacingOccurrencesOfString:@"," withString:@""];
    
    if ([allMoney intValue]>_DrawMaxMoney) {
        self.moneyTextField.text=[NSString stringWithFormat:@"%d",_DrawMaxMoney];

    }else{
        self.moneyTextField.text=allMoney;

    }

}

-(void)reloadUserMoney{
    MCUserMoneyModel * money_model=[MCUserMoneyModel sharedMCUserMoneyModel];
    [money_model refreashDataAndShow];
    self.money_model=money_model;
    
    NSString * num=money_model.LotteryMoney;
    _moneyLabel.text= [MCMathUnits GetMoneyShowNum:num];
    
    __weak __typeof(self)wself = self;
    
    money_model.callBackSuccessBlock = ^(id manager) {
        
        wself.money_model.FreezeMoney=manager[@"FreezeMoney"];
        wself.money_model.LotteryMoney=manager[@"LotteryMoney"];
        NSString * num=manager[@"LotteryMoney"];
        wself.moneyLabel.text= [MCMathUnits GetMoneyShowNum:num];
        
    };
}


@end
